package com.jinbai.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.util.DBUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/studio/album/display.json")
public class DisplayJsonServlet extends HttpServlet {
    private static class ResultView {
        public String cover;
        public List<String> tids;

        public ResultView(String cover, List<String> tids) {
            this.cover = cover;
            this.tids = tids;
        }
    }

    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        final String aid = req.getParameter("aid");
        // 寻找到该专辑中所有的音频以及其对应的类型
        List<String> tids = new ArrayList<>();
        String cover = "";
        try (Connection con = DBUtil.connection()) {
            {
                String sql = "select tid from relations where aid = ? order by tid desc ";
                try (PreparedStatement ps = con.prepareStatement(sql)) {
                    ps.setString(1, aid);
                    try (final ResultSet rs = ps.executeQuery()) {
                        while (rs.next()) {
                            tids.add(rs.getString("tid"));
                        }
                    }
                }
            }
            {
                String sql = "select cover from albums where aid = ?";
                try (PreparedStatement ps = con.prepareStatement(sql)) {
                    ps.setString(1, aid);
                    final ResultSet rs = ps.executeQuery();
                    rs.next();
                    cover = rs.getString("cover");
                }
            }
        }
        ResultView resultView = new ResultView(cover, tids);
        ObjectMapper objectMapper = new ObjectMapper();
        final String json = objectMapper.writeValueAsString(resultView);
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
